package 线程;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

public class ExchangerDemo {
    public static void main(String[] args) {
        final Exchanger<List> exchanger = new Exchanger<>();
        new Thread() {
            public void run() {
                List list = new ArrayList(2);
                list.add(1);
                list.add(2);
                try {
                    list = exchanger.exchange(list);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread1:" + list);
            }
        }.start();
        new Thread() {
            public void run() {
                List list = new ArrayList(3);
                list.add(3);
                list.add(4);
                list.add(5);
                try {
                    list = exchanger.exchange(list);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread2:" + list);
            }
        }.start();
    }
}